import { API } from './API';
import { router } from '../router';
import { useRootStore } from '../store';

const store = useRootStore();

// 获取基本信息
API.invoke('get-baseInfo').then((obj) => {
	store.setId(obj.id);
	store.setName(obj.name);
	store.setVersion(obj.version);

	if (obj.filePath) {
		getDocumentInfo(obj.filePath);
	}

	// 设置配色模式
	store.setColorScheme(obj.state.colorScheme, true);
});

// 获取配置文件值
API.invoke('get-config-file').then((value) => {
	store.setConfigFile(value);
});

// 消息
API.on('message', (_event, type, obj) => {
	store.setMessage(type, obj);
});

// 设置基本信息
API.on('set-fileInfo', (_event, arr) => {
	store.setFilePaht(arr[0].filePath);
	store.setFileInfo(arr[0]);
	store.setFileInfoMessageId(arr[1]);
});

// 工作完成
API.on('work-completed', (_event) => {
	store.setWork(false, null);

	router.push('/work');
});

// log 数据
API.on('log-data', (_event, data) => {
	console.log(data);
});

window.addEventListener('drop', (event) => {
	event.preventDefault();
	if (event.dataTransfer && event.dataTransfer.files) {
		const paths: string[] = [];

		for (let i = 0; i < event.dataTransfer.files.length; i++) {
			paths.push(event.dataTransfer.files[i].path);
		}

		if (paths.length > 0) {
			if (!store.isWork) {
				API.invoke('is-md-file-path', paths[0]).then((b) => {
					if (b) {
						getDocumentInfo(paths.shift() as string);
					}
				});

				if (paths.length > 1) API.send('drop-file', paths);
			} else {
				API.send('drop-file', paths);
			}
		}
	}
});

window.addEventListener('dragover', (event) => {
	event.preventDefault();
});

/**
 * 获取文件信息
 */
export const getDocumentInfo = (filePath: string) => {
	API.invoke('get-document-info', filePath).then((arr) => {
		store.setFilePaht(arr[0].filePath);
		store.setFileInfo(arr[0]);
		store.setFileInfoMessageId(arr[1]);
	});
};

/**
 * 创建窗口
 */
export const createWindow = (paths: (string | undefined)[]) => {
	API.send('create-window', paths);
};

// 展示路径
export const showPath = (path: string) => {
	API.send('show-path', path);
};
